package top.natsu.reminder.handler;/**
 * @author shikanatsu
 * @create 2022/3/28 0028 18:13
 */

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Singleton;
import lombok.Data;
import lombok.experimental.Accessors;
import top.natsu.reminder.common.constant.HookType;
import top.natsu.reminder.common.entity.WorkConfig;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description 当前监听记录存储 (单例模式保证各个线程获取)
 * @Author shikanatsu
 * @Date 2022/3/28 0028 18:13
 **/
@Data
@Accessors(chain = true)
public class TimeRecord {

    private static volatile TimeRecord timeRecord;

    private static ReentrantLock rlcok = new ReentrantLock();

    private TimeRecord() {
    }

    public static TimeRecord getInstance() {
        if (timeRecord == null) {
            synchronized (Singleton.class) {
                if (timeRecord == null) {
                    timeRecord = new TimeRecord();
                }
            }
        }
        return timeRecord;
    }


    /**
     * 当前操作的
     **/
    private AtomicInteger operationId = new AtomicInteger(0);

    /**
     * 最后记录的ID
     **/
    private String lastId;

    /**
     * 最后操作时间
     **/
    private volatile Date lastTime = null;

    /**
     * 最后操作类型
     **/
    private volatile HookType lastOperationType = null;

    /**
     * 当前已经工作时间
     **/
    private volatile String nowWorkTime ;


    private volatile Date startTime;


    /**
     * 疲劳值
     **/
    private volatile AtomicInteger fatigue = new AtomicInteger(0);


    private WorkConfig workConfig;

    /** 强制关闭后,下次休息时间 **/
    private Date nextRestTime;


    public void setOperation(Date time, HookType hookType) {
        rlcok.lock();
        try {
            this.lastTime = time;
            this.lastOperationType = hookType;
            this.operationId.getAndIncrement();
        } catch (Exception e) {
        } finally {
            rlcok.unlock();
        }
    }


    public TimeRecord bindWorkConfig(WorkConfig config) {
        this.workConfig = config;
        return this;
    }

    public void reSetFatigue() {
        this.fatigue.set(0);
    }


    public String getNowWorkTime() {
        long between = DateUtil.between(startTime, new Date(), DateUnit.MS);
//        String hour = DateUtil.formatBetween(between, BetweenFormatter.Level.HOUR);
        String minute = DateUtil.formatBetween(between, BetweenFormatter.Level.MINUTE);
        return " "+ minute ;
    }
}
